import { User, Log, UserManager } from "oidc-client";
import {Router} from "vue-router";


export class OidcAuth{
  
  static userManager:UserManager;
  static user:User|null;
  //static authName="main";

//export let user:User;

async initUserManager(router:Router){
  if(OidcAuth.userManager===undefined)
  {
  const loca = "https://localhost:5001"; //window.location.origin;
  const configUrl = `${loca}/_configuration/vue`;
  const response = await fetch(configUrl);
  const setting = await response.json();
  const mgr = new UserManager(setting);
  OidcAuth.userManager = mgr;
  this.useRouter(router);
  return mgr;
  }
}

isAuthenticated() {
  return !!OidcAuth.user && !OidcAuth.user.expired
}

signInRedirect(args: any) {
   return OidcAuth.userManager.signinRedirect ();
}

async getUser(){
  if(OidcAuth.userManager!==undefined)
  {
    if(OidcAuth.user===undefined)
      OidcAuth.user = await OidcAuth.userManager.getUser();
  }
  return OidcAuth.user;
}


async signinRedirectCallback()
{
  return await OidcAuth.userManager.signinRedirectCallback();
}

useRouter(router:Router){
  const myRouter = router
  const guard = (to: { matched: any[]; fullPath: any; }, from: any, next: any) => {
    if (to.matched.some(record => record.meta.auth !== undefined )) {
      if (this.isAuthenticated()) {
        next();
      } else {
        Log.debug(
          `auth anon user entering protected route ${to.fullPath}`
        )
        this.signInRedirect({ state: { to } })
          .then(() => {
              next(false)
          })
          .catch(() => next(false))
      }
    } else {
      next()
    }
  }
  router.beforeEach(guard);
}
}
const oidcAuth = new OidcAuth();
export default oidcAuth;
